package com.erebus.login.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erebus.login.mapper.StudentMapper;
import com.erebus.login.mapper.TeacherMapper;
import com.erebus.login.model.dto.AuthParamsDto;
import com.erebus.login.model.dto.UserExt;
import com.erebus.login.model.po.Student;
import com.erebus.login.model.po.Teacher;
import com.erebus.login.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

// 账号密码认证
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;



    @Override
    public UserExt execute(AuthParamsDto authParamsDto) {
        if (authParamsDto.getCategory() == 0) { // 学生
            Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>().eq(Student::getUserName, authParamsDto.getUsername()));
            //查询用户不存在, 返回null,
            if (student == null) {
                throw new RuntimeException("账号不存在");
            }
            //密码是否正确
            //查询到用户 拿到正确密码
            String passwordDb = student.getPassword();
            // 比对密码
            if(!passwordDb.equals(authParamsDto.getPassword())){
                throw new RuntimeException("密码错误");
            }

            UserExt userExt = new UserExt();
            BeanUtils.copyProperties(authParamsDto, userExt);

            return userExt;
        }

        Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>().eq(Teacher::getUserName, authParamsDto.getUsername()));
        //查询用户不存在, 返回null,
        if (teacher == null) {
            throw new RuntimeException("账号不存在");
        }
        //密码是否正确
        //查询到用户 拿到正确密码
        String passwordDb = teacher.getPassword();
        // 比对密码
        if(!passwordDb.equals(authParamsDto.getPassword())){
            throw new RuntimeException("密码错误");
        }

        UserExt userExt = new UserExt();
        BeanUtils.copyProperties(authParamsDto, userExt);

        return userExt;
    }

}
